package com.leoman.controller;

import com.leoman.common.factory.DataTableFactory;
import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.entity.Type;
import com.leoman.service.TypeService;
import com.leoman.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 分类controller
 * Created by 涂奕恒 on 2015/7/29.
 */
@Controller
@RequestMapping(value = "admin/type")
public class TypeController extends CommonController {

    @Autowired
    private TypeService typeService;

    @RequestMapping(value = "/index")
    public String index() {
        return "反馈类型列表";
    }

    @RequestMapping("/list")
    public void list(HttpServletResponse response,
                     Integer draw,
                     Integer start,
                     Integer length) {
        if (null == start || start == 0) {
            start = 1;
        }
        int pageNum = getPageNum(start, length);
        Page<Type> page = typeService.findList(pageNum, length);

        Map<String, Object> result = DataTableFactory.fitting(draw, page);
        WebUtil.printJson(response, result);
    }

    @RequestMapping("/save")
    @ResponseBody
    public Integer save(Integer id, String name) {
        try {
            Type type;

            if (null == id) {
                type = new Type();
            } else {
                type = typeService.getById(id);
            }

            type.setName(name);
            type.setIsCut(Constant.IS_CUT_NO);

            typeService.update(type);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Integer delete(Integer id) {
        try {
            typeService.deleteById(id);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
